using System;
using System.Collections.Generic;
using System.Text;

namespace LiJ.Framework.Msg.Mos
{
	/// <summary>
	/// 被动回复
	/// </summary>
	public class WxBaseReplyMsg : WxBaseMsg
	{
		private IDictionary<string, object> _propertyList;

		/// <summary>
		/// 自定义索引，获取指定字段的值
		/// </summary>
		/// <param name="key"></param>
		public object this[string key]
		{
			set
			{
				if (value != null)
				{
					this._propertyList[key] = value;
				}
			}
		}

		protected virtual void SetValueToXml()
		{
		}

		/// <summary>
		/// 转化为XML
		/// </summary>
		/// <returns></returns>
		public virtual string ToReplyXml()
		{
			this._propertyList = new Dictionary<string, object>();
			this["ToUserName"] = base.ToUserName;
			this["FromUserName"] = base.FromUserName;
			this["MsgType"] = base.MsgType;
			this["CreateTime"] = base.CreateTime;
			this.SetValueToXml();
			StringBuilder stringBuilder = new StringBuilder("<xml>");
			WxBaseReplyMsg.ProduceXml(stringBuilder, this._propertyList, null);
			stringBuilder.Append("</xml>");
			return stringBuilder.ToString();
		}

		private static void ProduceXml(StringBuilder xml, IDictionary<string, object> list, string keyName = null)
		{
			foreach (KeyValuePair<string, object> item in list)
			{
				if (item.Value != null)
				{
					Type type = item.Value.GetType();
					string value = keyName ?? item.Key;
					if (type.IsValueType)
					{
						xml.Append("<").Append(value).Append(">")
							.Append(item.Value)
							.Append("</")
							.Append(value)
							.Append(">");
					}
					else if (type.IsGenericType)
					{
						IDictionary<string, object> list2;
						Tuple<string, IDictionary<string, object>> tuple;
						if ((list2 = (item.Value as IDictionary<string, object>)) != null)
						{
							xml.Append("<").Append(value).Append(">");
							WxBaseReplyMsg.ProduceXml(xml, list2, null);
							xml.Append("</").Append(value).Append(">");
						}
						else if ((tuple = (item.Value as Tuple<string, IDictionary<string, object>>)) != null)
						{
							xml.Append("<").Append(value).Append(">");
							WxBaseReplyMsg.ProduceXml(xml, tuple.Item2, tuple.Item1);
							xml.Append("</").Append(value).Append(">");
						}
					}
					else
					{
						xml.Append("<").Append(value).Append(">")
							.Append("<![CDATA[")
							.Append(item.Value)
							.Append("]]>")
							.Append("</")
							.Append(value)
							.Append(">");
					}
				}
			}
		}
	}
}
